"""
成交量因子（量比）（用该周期的成交量除以过去十个交易日的同一时间段的交易量的平均值）
 另外一个是除以前十根k线的成交量均值吧
"""
import pandas as pd
import rqdatac as rq
from datetime import timedelta
from ..utility import make_domaint_time_dict


def self_get_factor_df(sec_id):
    symbol_time_dict = make_domaint_time_dict(sec_id)
    result_df = {}
    for symbol, time_dict in symbol_time_dict.items():
        prices = rq.get_price(symbol, start_date="20220801", end_date="20231116", frequency="1m",
                              fields="volume", expect_df=False)
        prices.index -= timedelta(minutes=1)
        date = prices.index.date
        time = prices.index.time
        prices = pd.DataFrame(prices)
        prices["date"] = date
        prices["time"] = time
        pv = prices.pivot(index="date", columns="time", values="volume")

        pv_mean = pv / pv.rolling(10, min_periods=1).mean()
        pv1 = pv_mean.reset_index()
        ml = pv1.melt(id_vars="date")

        dt = pd.to_datetime(ml["date"].astype(str) + " " + ml["time"].astype(str))
        ml["datetime"] = dt
        ml.sort_values(by="datetime", inplace=True)
        ml.set_index("datetime", inplace=True)
        volume1 = ml["value"]

        volume2 = prices["volume"] / prices["volume"].rolling(10, min_periods=10).mean()

        symbol_df = pd.DataFrame({"volume_1": volume1, "volume_2": volume2})
        symbol_df["symbol"] = symbol
        symbol_df = symbol_df[time_dict["start"]: time_dict["last"]]
        result_df[symbol] = symbol_df
    return pd.concat(list(result_df.values()))


def get_factor_df(sec_id, prices):
    print(sec_id, __file__)
    date = prices["close"].index.date
    time = prices["close"].index.time
    prices["date"] = date
    prices["time"] = time
    pv = prices.pivot(index="date", columns="time", values="volume")

    pv_mean = pv / pv.rolling(10, min_periods=1).mean()
    pv1 = pv_mean.reset_index()
    ml = pv1.melt(id_vars="date")

    dt = pd.to_datetime(ml["date"].astype(str) + " " + ml["time"].astype(str))
    ml["datetime"] = dt
    ml.sort_values(by="datetime", inplace=True)
    ml.set_index("datetime", inplace=True)

    prices["volume1"] = ml["value"]

    prices["volume2"] = prices["volume"] / prices["volume"].rolling(10, min_periods=10).mean()

    return prices
